package com.zadetk.helpyou.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zadetk.helpyou.App;
import com.zadetk.helpyou.R;
import com.zadetk.helpyou.base.AbsActivity;
import com.zadetk.helpyou.bean.RegsisterBean;
import com.zadetk.helpyou.bean.SendBean;
import com.zadetk.helpyou.net.BaseObserver;
import com.zadetk.helpyou.net.BaseResponse;
import com.zadetk.helpyou.net.NetTool;
import com.zadetk.helpyou.other.Const;
import com.zadetk.helpyou.other.UserInfoManger;
import com.zadetk.helpyou.utils.MD5;
import com.zadetk.helpyou.utils.SPUtil;
import com.zadetk.helpyou.utils.ToastUtil;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.zadetk.helpyou.other.Const.USER_IS_LOGIN;

/**
 * 2-2注册页面
 */
public class RegsisterActivity extends AbsActivity implements View.OnClickListener {
    private EditText etPhonenumber;
    private EditText etVerifycode;
    private TextView tvVirifycode;
    private EditText etPassword;
    private TextView tvBtnRegsister;
    private ImageView ivBack;
    private CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long l) {
            int ms = (int) (l / 1000);
            tvVirifycode.setText(ms + "s");
            tvVirifycode.setClickable(false);
        }

        @Override
        public void onFinish() {
            tvVirifycode.setText("发送验证码");
            tvVirifycode.setClickable(true);
        }
    };

    private void initViews() {
        etPhonenumber = (EditText) findViewById(R.id.et_phonenumber);
        etVerifycode = (EditText) findViewById(R.id.et_verifycode);
        tvVirifycode = (TextView) findViewById(R.id.tv_virifycode);
        etPassword = (EditText) findViewById(R.id.et_password);
        tvBtnRegsister = (TextView) findViewById(R.id.tv_btn_regsister);
        ivBack = findViewById(R.id.iv_back);
        setTopTitle("快速注册");
        //FIXME 注册页面测试代码
        etPhonenumber.setText("18642036697");
    }

    @Override
    public int setView() {
        return R.layout.activity_regsister;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initViews();
        initLogic();
    }

    private void initLogic() {
        tvVirifycode.setOnClickListener(this);
        tvBtnRegsister.setOnClickListener(this);
        ivBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(RegsisterActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                finish();
                break;
            case R.id.tv_virifycode:
                sendSmscode();
                break;
            case R.id.tv_btn_regsister:
                regsister();
                break;
        }
    }

    private void regsister() {
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(RegsisterActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
        String phone = etPhonenumber.getText().toString();
        String verifycode = etVerifycode.getText().toString();
        String password = etPassword.getText().toString();
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(verifycode) || TextUtils.isEmpty(password)) {
            ToastUtil.showToast("请完善信息后注册!");
            return;
        }
        Map<String, Object> param = NetTool.newParams();
        param.put("username", phone);
        param.put("password", MD5.getStringMD5(password));
        param.put("verifycode", verifycode);
        NetTool.getApi().regsister(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<RegsisterBean>>() {
                    @Override
                    public void onData(BaseResponse<RegsisterBean> value) {
                        if (value.getCode() == 0 && value.getData().getStatus() == 1) {
                            SPUtil.saveDate(RegsisterActivity.this, Const.USER_TOKEN, value.getData().getToken());
                            SPUtil.saveDate(RegsisterActivity.this, Const.USER_NAME, value.getData().getUsername());
                            ToastUtil.showToast("注册成功！自动回到主页面" + value.getMessage());
                            SPUtil.saveDate(RegsisterActivity.this, USER_IS_LOGIN, true);
                            SPUtil.saveDate(RegsisterActivity.this, Const.USER_UID, value.getData().getUid());
                            UserInfoManger.isLogin = true;
                            App.finishAllActivity();
                            startActivity(new Intent(RegsisterActivity.this, MainActivity.class));
                        } else {
                            ToastUtil.showToast("注册失败！" + value.getMessage());
                        }
                    }
                });
    }

    private void sendSmscode() {
        String phone = etPhonenumber.getText().toString();
        if(TextUtils.isEmpty(phone)){
            ToastUtil.showToast("请输入手机号码！");
            return;
        }
        else{
            if(!phoneCheck(Const.PHONE_CHECK,phone)){
                ToastUtil.showToast("请输入正确的手机号码！");
            }else{
                Map<String, Object> param = NetTool.newParams();
                param.put("phonenum",phone);
                NetTool.getApi().sendSmsCode(param)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<BaseResponse<SendBean>>() {
                            @Override
                            public void onData(BaseResponse<SendBean> value) {
                                if(value.getCode() == 0 && value.getData().getFlag() == 1){
                                    ToastUtil.showToast("发送成功！");
                                }else{
                                    ToastUtil.showToast("发送失败！");
                                }
                                startCount();
                            }
                        });
            }
        }
    }

    private void startCount() {
        countDownTimer.start();
    }

    public static boolean phoneCheck(String patttern, String username){
        Pattern pattern = Pattern.compile(patttern);
        Matcher matcher = pattern.matcher(username);
        if(matcher.find()){
            return  true;
        }
        else {
            return false;
        }
    }
}
